<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="60%"
    title="多单位设置"
    :style="{ top: '20px' }"
  >
    <div v-if="visible" v-permission="['base-data:product:unit:query']" v-loading="loading">
      <a-form
        ref="form"
        :label-col="{ span: 2 }"
        :wrapper-col="{ span: 18 }"
        :model="formData"
        :rules="rules"
      >
        <a-form-item label="单位">
          <unit-selector v-model:value="productData.unit" readOnly />
        </a-form-item>
        <a-form-item label="单位转换" name="assistantUnit">
          <vxe-grid
            ref="grid"
            resizable
            show-overflow
            highlight-hover-row
            keep-source
            :height="Math.min(Math.max(formData.assistantUnit.length, 4), 8) * 50 + 50"
            row-id="id"
            :columns="[
              { title: '转换方向', width: 150, formatter: () => '库存单位-->辅助单位' },
              { title: '数量', width: 60, align: 'center', formatter: () => '1' },
              { title: '库存单位', minWidth: 150, slots: { default: 'assistantUnitId_default' } },
              { title: '条件', width: 50, align: 'center', formatter: () => '=' },
              {
                title: '数量',
                field: 'unitVal',
                width: 100,
                slots: { default: 'unitVal_default' },
              },
              {
                title: '辅助单位',
                field: 'toUnitId',
                minWidth: 150,
                slots: { default: 'toUnitId_default' },
              },
              {
                title: '操作',
                width: 70,
                align: 'center',
                fixed: 'right',
                slots: { default: 'action_default' },
              },
            ]"
            :toolbar-config="{
              zoom: false,
              refresh: false,
              custom: false,
              slots: {
                buttons: 'toolbar_buttons',
              },
            }"
            :data="formData.assistantUnit"
          >
            <!-- 工具栏 -->
            <template #toolbar_buttons>
              <a-space>
                <a-button type="primary" @click="add">添加辅助单位</a-button>
              </a-space>
            </template>
            <!-- 库存单位 -->
            <template #assistantUnitId_default="{ rowIndex, row }">
              <a-form-item
                no-style
                :name="['assistantUnit', rowIndex, 'assistantUnitId']"
                :rules="[{ required: true, message: '请选择单位' }]"
              >
                <unit-selector v-model:value="row.assistantUnitId" />
              </a-form-item>
            </template>
            <!-- 数量 -->
            <template #unitVal_default="{ rowIndex, row }">
              <a-form-item
                no-style
                :name="['assistantUnit', rowIndex, 'unitVal']"
                :rules="{ required: true, message: '请填写单位数值' }"
              >
                <a-input-number style="width: 75px" precision="2" v-model:value="row.unitVal" />
              </a-form-item>
            </template>
            <!-- 辅助单位 -->
            <template #toUnitId_default="{ rowIndex, row }">
              <a-form-item
                no-style
                :name="['assistantUnit', rowIndex, 'toUnitId']"
                :rules="[{ required: true, message: '请选择转换单位' }]"
              >
                <unit-selector v-model:value="row.toUnitId" />
              </a-form-item>
            </template>
            <template #action_default="{ rowIndex }">
              <a-button
                type="link"
                @click="() => formData.assistantUnit.splice(rowIndex, 1)"
                danger
              >
                删除
              </a-button>
            </template>
          </vxe-grid>
        </a-form-item>
      </a-form>
    </div>
    <template #footer>
      <div class="form-modal-footer" v-permission="['base-data:product:spec:add']">
        <a-space>
          <a-button type="primary" :loading="loading" html-type="submit" @click="submit"
            >保存</a-button
          >
          <a-button :loading="loading" @click="closeDialog">取消</a-button>
        </a-space>
      </div>
    </template>
  </a-modal>
</template>

<script setup>
  import { getCurrentInstance, ref } from 'vue';
  import * as productApi from '@/api/base-data/product/info';
  import * as api from '@/api/base-data/product/unit';
  import UnitSelector from '@/components/Selector/src/UnitSelector.vue';

  // this对象
  const instance = getCurrentInstance();

  const emit = defineEmits(['confirm', 'close']);

  const visible = ref(false);

  // 加载中
  const loading = ref(false);

  // 商品信息
  const productData = ref({});

  const form = ref();

  //
  const formData = ref({
    unit: '',
    assistantUnit: [],
  });

  //
  const rules = ref({
    unit: [{ required: true, message: '请选择基础单位' }],
  });

  const props = defineProps({
    productId: {
      type: String,
      required: true,
    },
  });

  const add = () => {
    formData.value.assistantUnit.push({});
  };

  // 查询数据
  const loadFormData = (productId) => {
    loading.value = true;
    productApi
      .get(productId)
      .then((data) => {
        productData.value = data;
        formData.value.unit = data.unit;
        formData.value.assistantUnit = [];
        api
          .query({
            productId: productId,
          })
          .then((result) => {
            if (result) {
              formData.value.assistantUnit = result;
            }
          });
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 打开弹窗
  const openDialog = (productId) => {
    visible.value = true;
    loadFormData(productId);
  };

  // 数据提交
  const submit = () => {
    form.value.validate().then(() => {
      loading.value = true;
      api
        .save(props.productId, formData.value.assistantUnit)
        .then(() => {
          _This().$message.success('保存成功');
          emit('confirm');
          closeDialog();
        })
        .finally(() => {
          loading.value = false;
        });
    });
  };

  // 关闭对话框
  const closeDialog = () => {
    visible.value = false;
    emit('close');
  };

  // 组件实例对象
  const _This = () => {
    return instance.appContext.config.globalProperties;
  };

  defineExpose({
    openDialog,
  });
</script>

<style scoped></style>
